<template>
  <div class="test-formpost-container">
    <div class="test-formpost-card">
      <h2>Form Post响应模式测试</h2>
      
      <div class="test-section">
        <h3>当前配置</h3>
        <div class="config-info">
          <p><strong>客户端ID:</strong> {{ configInfo.clientId }}</p>
          <p><strong>租户ID:</strong> {{ configInfo.tenantId }}</p>
          <p><strong>重定向URI:</strong> {{ configInfo.redirectUri }}</p>
          <p><strong>响应模式:</strong> {{ configInfo.responseMode }}</p>
          <p><strong>Scope:</strong> {{ configInfo.scopes.join(', ') }}</p>
        </div>
      </div>

      <div class="test-section">
        <h3>测试操作</h3>
        <div class="test-actions">
          <button @click="testFormPostLogin" class="test-btn primary">测试Form Post登录</button>
          <button @click="testManualUrl" class="test-btn secondary">测试手动URL构建</button>
          <button @click="showAuthUrl" class="test-btn warning">显示授权URL</button>
        </div>
      </div>

      <div class="test-section" v-if="authUrl">
        <h3>生成的授权URL</h3>
        <div class="auth-url-display">
          <textarea v-model="authUrl" readonly class="auth-url-textarea"></textarea>
          <button @click="copyAuthUrl" class="copy-btn">复制URL</button>
        </div>
      </div>

      <div class="test-section" v-if="testResults.length > 0">
        <h3>测试结果</h3>
        <div class="test-results">
          <div v-for="(result, index) in testResults" :key="index" class="test-result">
            <span class="result-time">{{ result.time }}</span>
            <span :class="['result-status', result.success ? 'success' : 'error']">
              {{ result.success ? '✅' : '❌' }}
            </span>
            <span class="result-message">{{ result.message }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import msalService from '@/services/msalService';
import { msalConfig, loginRequestWithFormPost } from '@/config/msal-config';

const router = useRouter();

const configInfo = ref({
  clientId: import.meta.env.VITE_MS_365_CLIENT_ID || '未设置',
  tenantId: import.meta.env.VITE_MS_365_TENANT_ID || '未设置',
  redirectUri: msalConfig.auth.redirectUri,
  responseMode: loginRequestWithFormPost.responseMode,
  scopes: loginRequestWithFormPost.scopes
});

const testResults = ref<Array<{
  time: string;
  success: boolean;
  message: string;
}>>([]);

const authUrl = ref('');

onMounted(() => {
  console.log('🔧 TestFormPost页面已加载');
  console.log('🔧 配置信息:', configInfo.value);
  addTestResult(true, 'Form Post测试页面已加载');
  addTestResult(true, `客户端ID: ${configInfo.value.clientId}`);
  addTestResult(true, `租户ID: ${configInfo.value.tenantId}`);
  addTestResult(true, `响应模式: ${configInfo.value.responseMode}`);
  
  // 立即执行一个简单的测试
  setTimeout(() => {
    testManualUrl();
  }, 1000);
  
  // 添加全局测试函数
  (window as any).testFormPostUrl = () => {
    console.log('🔧 执行全局测试函数...');
    testManualUrl();
  };
  
  console.log('🔧 全局测试函数已添加，可在控制台运行: testFormPostUrl()');
});

function addTestResult(success: boolean, message: string) {
  testResults.value.unshift({
    time: new Date().toLocaleTimeString(),
    success,
    message
  });
}

async function testFormPostLogin() {
  try {
    addTestResult(true, '开始Form Post登录测试...');
    
    // 检查配置
    console.log('🔧 Form Post登录配置:', {
      responseMode: loginRequestWithFormPost.responseMode,
      scopes: loginRequestWithFormPost.scopes,
      redirectUri: msalConfig.auth.redirectUri
    });
    
    addTestResult(true, `响应模式: ${loginRequestWithFormPost.responseMode}`);
    addTestResult(true, `Scope: ${loginRequestWithFormPost.scopes.join(', ')}`);
    
    // 执行登录
    await msalService.login();
    addTestResult(true, 'Form Post登录重定向已触发');
    
  } catch (error: any) {
    console.error('❌ Form Post登录测试失败:', error);
    addTestResult(false, `登录失败: ${error.message}`);
  }
}

function testManualUrl() {
  try {
    addTestResult(true, '测试手动URL构建...');
    
    // 手动构建授权URL
    const clientId = msalConfig.auth.clientId;
    const tenantId = import.meta.env.VITE_MS_365_TENANT_ID || '';
    const redirectUri = encodeURIComponent(msalConfig.auth.redirectUri || '');
    const scopes = encodeURIComponent(loginRequestWithFormPost.scopes.join(' '));
    const state = Math.random().toString(36).substring(2, 15);
    const nonce = Math.random().toString(36).substring(2, 15);
    
    const manualUrl = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/authorize?` +
      `client_id=${clientId}&` +
      `scope=${scopes}&` +
      `redirect_uri=${redirectUri}&` +
      `response_type=code&` +
      `response_mode=form_post&` +
      `state=${state}&` +
      `nonce=${nonce}&` +
      `prompt=login&` +
      `client_info=1`;
    
    authUrl.value = manualUrl;
    addTestResult(true, '手动URL构建成功');
    addTestResult(true, `URL包含response_mode=form_post: ${manualUrl.includes('response_mode=form_post')}`);
    
  } catch (error: any) {
    console.error('❌ 手动URL构建失败:', error);
    addTestResult(false, `URL构建失败: ${error.message}`);
  }
}

function showAuthUrl() {
  try {
    addTestResult(true, '显示授权URL...');
    
    // 使用MSAL服务构建URL
    const clientId = msalConfig.auth.clientId;
    const tenantId = import.meta.env.VITE_MS_365_TENANT_ID || '';
    const redirectUri = encodeURIComponent(msalConfig.auth.redirectUri || '');
    const scopes = encodeURIComponent(loginRequestWithFormPost.scopes.join(' '));
    const state = Math.random().toString(36).substring(2, 15);
    const nonce = Math.random().toString(36).substring(2, 15);
    
    const msalUrl = `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/authorize?` +
      `client_id=${clientId}&` +
      `scope=${scopes}&` +
      `redirect_uri=${redirectUri}&` +
      `response_type=code&` +
      `response_mode=form_post&` +
      `state=${state}&` +
      `nonce=${nonce}&` +
      `prompt=login&` +
      `client_info=1`;
    
    authUrl.value = msalUrl;
    addTestResult(true, 'MSAL授权URL构建成功');
    addTestResult(true, `URL包含response_mode=form_post: ${msalUrl.includes('response_mode=form_post')}`);
    
  } catch (error: any) {
    console.error('❌ MSAL URL构建失败:', error);
    addTestResult(false, `URL构建失败: ${error.message}`);
  }
}

function copyAuthUrl() {
  if (authUrl.value) {
    navigator.clipboard.writeText(authUrl.value).then(() => {
      addTestResult(true, '授权URL已复制到剪贴板');
    }).catch(() => {
      addTestResult(false, '复制URL失败');
    });
  }
}
</script>

<style scoped>
.test-formpost-container {
  min-height: 100vh;
  padding: 2rem;
  background: linear-gradient(135deg, #f5f5f5 0%, #e0e0e0 100%);
}

.test-formpost-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  padding: 2rem;
  max-width: 900px;
  margin: 0 auto;
}

.test-formpost-card h2 {
  text-align: center;
  color: #333;
  margin-bottom: 2rem;
}

.test-section {
  margin-bottom: 2rem;
  padding: 1rem;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
}

.test-section h3 {
  color: #555;
  margin-bottom: 1rem;
  border-bottom: 2px solid #0d6efd;
  padding-bottom: 0.5rem;
}

.config-info p {
  margin: 0.5rem 0;
  font-family: monospace;
  background: #f8f9fa;
  padding: 0.5rem;
  border-radius: 4px;
}

.test-actions {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
}

.test-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
}

.test-btn.primary {
  background: #0d6efd;
  color: white;
}

.test-btn.primary:hover {
  background: #0b5ed7;
}

.test-btn.secondary {
  background: #6c757d;
  color: white;
}

.test-btn.secondary:hover {
  background: #5a6268;
}

.test-btn.warning {
  background: #ffc107;
  color: #212529;
}

.test-btn.warning:hover {
  background: #e0a800;
}

.auth-url-display {
  display: flex;
  gap: 1rem;
  align-items: flex-start;
}

.auth-url-textarea {
  flex: 1;
  min-height: 120px;
  padding: 1rem;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  font-family: monospace;
  font-size: 12px;
  resize: vertical;
}

.copy-btn {
  padding: 10px 20px;
  background: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.copy-btn:hover {
  background: #218838;
}

.test-results {
  max-height: 300px;
  overflow-y: auto;
}

.test-result {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 0.5rem;
  border-bottom: 1px solid #e0e0e0;
}

.test-result:last-child {
  border-bottom: none;
}

.result-time {
  font-size: 12px;
  color: #666;
  min-width: 80px;
}

.result-status {
  font-size: 16px;
  min-width: 20px;
}

.result-status.success {
  color: #28a745;
}

.result-status.error {
  color: #dc3545;
}

.result-message {
  flex: 1;
  font-size: 14px;
}
</style> 